#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/12/21 14:41
# @Author  : tianqunhui
# @contact : tqunhui@qq.com
# @File    : tianqunhui_04.py
# @Software: PyCharm

import time

date_num = '19990229'

def search_birthday(number):
    if number:
        is_in = pi_str.find(number)
        if is_in == -1:
            return False
        else:
            print('距离生日[ %s ]最近的日期为[ %s ], 位置为[ %s ]'% (date_num, number, pi_str.index(number)))
            return True
    else:
        return False


def is_valid_date(str):
  '''判断是否是一个有效的日期字符串'''
  n = int(str)
  if 19800101 <= n <= 20001231:
      pass
  else:
      return False

  # 时间插入-
  str = str[0:4] + '-' + str[4:6] + '-' + str[6:8]

  try:
    time.strptime(str, "%Y-%m-%d")
    return True
  except:
    return False


if __name__ == '__main__':
    # 打开文件
    pi_str = ''
    with open('pi.txt', 'r', encoding='utf-8') as f:
        sss = f.readlines()

    for line in sss:
        pi_str += line.rstrip()


    num = date_num
    # 判断输入格式是否正确
    if num.isdigit():
        n = int(num)
        if 19800101 <= n <= 20001231:
            is_exist = search_birthday(num)
            is_valid_date_flag = True
            while not is_exist:
                n = n+1
                new_num = str(n)
                is_valid_date_flag = is_valid_date(new_num)
                if is_valid_date_flag:
                    is_exist = search_birthday(new_num)
                if is_exist:
                    break

                n = n - 2
                new_num = str(n)
                is_valid_date_flag = is_valid_date(new_num)
                if is_valid_date_flag:
                    is_exist = search_birthday(new_num)
                if is_exist:
                    break

            if not is_exist:
                print('不存在')

        else:
            print("时间超过规定时间段")
    else:
        print("时间输入有错")


# 输入    date_num = '19990229'
# 输出    距离生日[ 19990229 ]最近的日期为[ 19990220 ], 位置为[ 724004 ]